package com.loan.market.view

import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import androidx.core.view.updateLayoutParams
import com.loan.market.R
import com.loan.market.databinding.LayoutStepBinding

class StepView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : LinearLayout(context, attrs) {

    private var binding: LayoutStepBinding

    init {
        orientation = VERTICAL
        inflate(context, R.layout.layout_step, this)
        binding = LayoutStepBinding.bind(this)
    }

    fun setStep(s: Int) {
        val step = if (s < 0) 0 else if (s > 10) 10 else s
        binding.tvPercent.text = (step * 10).toString() + "%"
        binding.tvPercent.post {
            val width = width
            binding.tvPercent.updateLayoutParams<LayoutParams> {
                leftMargin = if (step < 1) {
                    0
                } else if (step >= binding.llStep.childCount) {
                    width - binding.tvPercent.width
                } else {
                    (step.toFloat() / binding.llStep.childCount * width - binding.tvPercent.width / 2).toInt()
                }
            }
        }
        for (i in 0 until binding.llStep.childCount) {
            binding.llStep.getChildAt(i).isSelected = i <= step - 1
        }
    }

}